from django.shortcuts import render
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import Coupon,CouponType,CouponTypeValue,GetCoupon
from .serializers import CouPonSer,GetSer,TypeSer,ValueSer
from sku.models import Good
from sku.serializers import GoodSer
# Create your views here.
class AllSku(APIView):
    def get(self,request):
        data = Good.objects.all()
        ser = GoodSer(data,many=True)
        return Response(ser.data)


class CouponTypeView(APIView):
    def get(self,request):
        data = CouponType.objects.all()
        ser = TypeSer(data,many=True)
        return Response(ser.data)


class AddCoupon(APIView):
    def post(self,request):
        data = request.data
        ser = CouPonSer(data=data)
        if ser.is_valid(raise_exception=True):
            ser.save()
            return Response({'msg':'添加成功','code':200})
        else:
            return Response({'msg':'参数不合法','code':400})

class GetCouponView(APIView):
    def get(self,request):
        page = int(request.query_params.get('page'))
        pages = int(request.query_params.get('pages'))
        data = Coupon.objects.all()[((page-1)*pages):(page*pages)]
        ser = CouPonSer(data,many=True)
        return Response({'data':ser.data,'count':Coupon.objects.all().count()})


class OneCouponView(APIView):
    def get(self,request,id):
        try:
            data = Coupon.objects.get(id=id)
            ser = CouPonSer(data)
            return Response({'data':ser.data,'code':200})
        except Exception as e:
            print(e)
            return Response({'msg':'获取失败','code':204})
    def put(self,request,id):
        data = request.data
        try:
            Coupon.objects.filter(id=id).update(
                name=data.get('name'),
                brief=data.get('brief'),
                coupon_type=data.get('coupon_type'),
                good_id = data.get('good'),
                coupon_num=data.get('coupon_num'),
                start_time=data.get('start_time'),
                over_time=data.get('over_time'),
                start_get_time=data.get('start_get_time'),
                end_get_time=data.get('end_get_time'),
                remark=data.get('remark')
            )
            return Response({'msg': '修改成功', 'code': 200})
        except Exception as e:
            print(e)
            return Response({'msg':'修改失败','code':204})